package BookFrame;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DetailBook extends JDialog {
    // 图书基础信息组件
    protected JTextField bookIdField = new JTextField(15);  // 图书编号
    protected JTextField titleField = new JTextField(15);    // 书名
    protected JComboBox<String> categoryCombo = new JComboBox<>(new String[]{"", "文学", "科技", "教育", "历史", "艺术"}); // 分类
    protected JRadioButton inStockRadio = new JRadioButton("在架");  // 库存状态
    protected JRadioButton borrowedRadio = new JRadioButton("借阅中", true);
    protected JTextField stockField = new JTextField(15);     // 库存数量
    protected JTextField locationField = new JTextField(15);   // 存放位置

    // 借阅信息组件
    protected JTextField borrowerIdField = new JTextField(15); // 借阅者编号
    protected JTextField borrowDateField = new JTextField(15); // 借阅日期
    protected JTextField dueDateField = new JTextField(15);    // 应还日期

    // 操作按钮
    JButton saveBtn = new JButton("保存");
    JButton resetBtn = new JButton("重置");
    JButton cancelBtn = new JButton("取消");

    public DetailBook(Book book) {
        this();
        setTitle("图书详情");
        saveBtn.setText("更新图书信息");
        resetBtn.setVisible(false);
        cancelBtn.setText("返回");
        setDefaultValues(book); // 填充现有图书信息
        setComponentsUneditable(); // 详情界面默认不可编辑
    }

    public DetailBook() {
        setSize(600, 400);
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((dimension.width - getWidth()) / 2, (dimension.height - getHeight()) / 2);
        setTitle("添加新图书");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout());

        // 中央内容面板（左右分栏）
        JPanel centerPanel = new JPanel(new GridLayout(1, 2, 10, 10));
        JPanel leftPanel = new JPanel();
        JPanel rightPanel = new JPanel();
        centerPanel.add(leftPanel);
        centerPanel.add(rightPanel);
        add(centerPanel, BorderLayout.CENTER);

        // 左侧：基础信息面板
        Border etchedBorder = BorderFactory.createEtchedBorder();
        leftPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder, "图书基础信息"));
        leftPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));

        // 图书编号（新增时可编辑，更新时不可编辑）
        JPanel row1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        row1.add(new JLabel("图书编号："));
        row1.add(bookIdField);
        leftPanel.add(row1);

        // 书名
        JPanel row2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        row2.add(new JLabel("书名："));
        row2.add(titleField);
        leftPanel.add(row2);

        // 分类
        JPanel row3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        row3.add(new JLabel("分类："));
        row3.add(categoryCombo);
        leftPanel.add(row3);

        // 库存状态
        JPanel row4 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        row4.add(new JLabel("状态："));
        ButtonGroup statusGroup = new ButtonGroup();
        statusGroup.add(inStockRadio);
        statusGroup.add(borrowedRadio);
        row4.add(inStockRadio);
        row4.add(borrowedRadio);
        leftPanel.add(row4);

        // 库存数量
        JPanel row5 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        row5.add(new JLabel("库存："));
        row5.add(stockField);
        leftPanel.add(row5);

        // 存放位置
        JPanel row6 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        row6.add(new JLabel("位置："));
        row6.add(locationField);
        leftPanel.add(row6);

        // 右侧：借阅信息面板
        rightPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder, "借阅信息"));
        rightPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));

        // 借阅者编号
        JPanel borrowRow1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        borrowRow1.add(new JLabel("借阅者编号："));
        borrowRow1.add(borrowerIdField);
        rightPanel.add(borrowRow1);

        // 借阅日期
        JPanel borrowRow2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        borrowRow2.add(new JLabel("借阅日期："));
        borrowRow2.add(borrowDateField);
        rightPanel.add(borrowRow2);

        // 应还日期
        JPanel borrowRow3 = new JPanel(new FlowLayout(FlowLayout.LEFT));
        borrowRow3.add(new JLabel("应还日期："));
        borrowRow3.add(dueDateField);
        rightPanel.add(borrowRow3);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 5));
        buttonPanel.add(saveBtn);
        buttonPanel.add(resetBtn);
        buttonPanel.add(cancelBtn);
        add(buttonPanel, BorderLayout.SOUTH);

        // 事件监听
        saveBtn.addActionListener(new ButtonListener(this));
        resetBtn.addActionListener(new ButtonListener(this));
        cancelBtn.addActionListener(new ButtonListener(this));
    }

    /** 设置默认值（用于更新图书时填充数据） */
    private void setDefaultValues(Book book) {
        bookIdField.setText(String.valueOf(book.getBookId()));
        titleField.setText(book.getTitle());
        categoryCombo.setSelectedItem(book.getCategory());
        inStockRadio.setSelected(book.getStatus().equals("在架"));
        borrowedRadio.setSelected(book.getStatus().equals("借阅中"));
        stockField.setText(String.valueOf(book.getStock()));
        locationField.setText(book.getLocation());
        borrowerIdField.setText(String.valueOf(book.getBorrowerId()));
        borrowDateField.setText(book.getBorrowDate());
        dueDateField.setText(book.getDueDate());
    }

    /** 设置组件不可编辑（详情模式） */
    private void setComponentsUneditable() {
        bookIdField.setEditable(false);
        titleField.setEditable(false);
        categoryCombo.setEnabled(false);
        inStockRadio.setEnabled(false);
        borrowedRadio.setEnabled(false);
        stockField.setEditable(false);
        locationField.setEditable(false);
        borrowerIdField.setEditable(false);
        borrowDateField.setEditable(false);
        dueDateField.setEditable(false);
    }

    /** 设置组件可编辑（新增/更新模式） */
    private void setComponentsEditable() {
        titleField.setEditable(true);
        categoryCombo.setEnabled(true);
        inStockRadio.setEnabled(true);
        borrowedRadio.setEnabled(true);
        stockField.setEditable(true);
        locationField.setEditable(true);
        borrowerIdField.setEditable(true);
        borrowDateField.setEditable(true);
        dueDateField.setEditable(true);
        // 新增时允许编辑图书编号，更新时不可编辑
        if (bookIdField.getText().isEmpty()) {
            bookIdField.setEditable(true);
        }
    }

    /** 事件监听内部类 */
    class ButtonListener implements ActionListener {
        private DetailBook dialog;

        public ButtonListener(DetailBook dialog) {
            this.dialog = dialog;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (command.equals("保存")) {
                // 新增图书逻辑
                Book newBook = createBookFromForm();
                if (Dao.getInstance().bookIdHasExist(newBook.getBookId())) {
                    JOptionPane.showMessageDialog(null, "图书编号已存在，请重新输入！");
                    return;
                }
                Dao.getInstance().addBook(newBook);
                JOptionPane.showMessageDialog(null, "图书添加成功！");
                dialog.dispose();
            } else if (command.equals("更新图书信息")) {
                // 切换为可编辑模式
                setComponentsEditable();
                saveBtn.setText("保存更新");
                cancelBtn.setText("取消");
            } else if (command.equals("保存更新")) {
                // 更新图书逻辑
                Book updatedBook = createBookFromForm();
                Dao.getInstance().updateBookInfo(updatedBook);
                JOptionPane.showMessageDialog(null, "图书信息已更新！");
                dialog.dispose();
            } else if (command.equals("重置")) {
                // 清空表单
                resetFields();
            } else if (command.equals("取消") || command.equals("返回")) {
                // 关闭窗口
                dialog.dispose();
            }
        }

        /** 从表单获取数据创建Book对象 */
        private Book createBookFromForm() {
            Book book = new Book();
            book.setBookId(Integer.parseInt(bookIdField.getText()));
            book.setTitle(titleField.getText());
            book.setCategory((String) categoryCombo.getSelectedItem());
            book.setStatus(inStockRadio.isSelected() ? "在架" : "借阅中");
            book.setStock(Integer.parseInt(stockField.getText()));
            book.setLocation(locationField.getText());
            book.setBorrowerId(Integer.parseInt(borrowerIdField.getText()));
            book.setBorrowDate(borrowDateField.getText());
            book.setDueDate(dueDateField.getText());
            return book;
        }

        /** 重置表单字段 */
        private void resetFields() {
            bookIdField.setText("");
            titleField.setText("");
            categoryCombo.setSelectedIndex(0);
            inStockRadio.setSelected(true);
            stockField.setText("");
            locationField.setText("");
            borrowerIdField.setText("");
            borrowDateField.setText("");
            dueDateField.setText("");
        }
    }

    public static void main(String[] args) {
        // 测试：新建图书界面
        new DetailBook().setVisible(true);
    }
}
